/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.classifyQuestion;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang3.Validate;

import ru.irenproject.FormulationSupplier;
import ru.irenproject.Question;
import ru.irenproject.TestCheck;
import ru.irenproject.classifyQuestion.ClassifyQuestionProtos.Category;
import ru.irenproject.pad.Pad;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Event;
import ru.irenproject.store.Stash;

import com.google.protobuf.ByteString;

public final class ClassifyQuestion extends AbstractThing
    implements Question, FormulationSupplier {
  public enum ChangeEvent implements Event { INSTANCE }

  public static final int MAX_CATEGORIES = 10;
  public static final int MAX_ITEMS = 100;

  @Stash private ClassifyQuestionProtos.ClassifyQuestion.Builder $;

  @Inject ClassifyQuestion() {}

  @Override protected void initialize() {
    Pad formulation = store().create(Pad.class);
    $.setFormulation(formulation.id());
  }

  @Override public Pad formulation() {
    return get($.getFormulation(), Pad.class);
  }

  public int categoryCount() {
    return $.getCategoryCount();
  }

  public int addCategory() {
    TestCheck.input(categoryCount() < MAX_CATEGORIES);

    Pad title = store().create(Pad.class);
    $.addCategoryBuilder().setTitle(title.id());
    post(ChangeEvent.INSTANCE);

    return categoryCount() - 1;
  }

  public Pad getCategoryTitle(int categoryIndex) {
    checkCategoryIndex(categoryIndex);
    return get($.getCategoryBuilder(categoryIndex).getTitle(), Pad.class);
  }

  private void checkCategoryIndex(int index) {
    TestCheck.input(index >= 0);
    TestCheck.input(index < categoryCount());
  }

  public Pad addItem(int categoryIndex) {
    checkCategoryIndex(categoryIndex);
    TestCheck.input(totalItemCount() < MAX_ITEMS);

    Pad res = store().create(Pad.class);
    $.getCategoryBuilder(categoryIndex).addItem(res.id());
    post(ChangeEvent.INSTANCE);

    return res;
  }

  public int totalItemCount() {
    int res = 0;
    for (Category.Builder c : $.getCategoryBuilderList()) {
      res += c.getItemCount();
    }
    return res;
  }

  public int getItemCount(int categoryIndex) {
    checkCategoryIndex(categoryIndex);
    return $.getCategoryBuilder(categoryIndex).getItemCount();
  }

  public Pad getItem(int categoryIndex, int itemIndex) {
    checkItemIndex(categoryIndex, itemIndex);
    return get($.getCategoryBuilder(categoryIndex).getItem(itemIndex), Pad.class);
  }

  private void checkItemIndex(int categoryIndex, int itemIndex) {
    TestCheck.input(itemIndex >= 0);
    TestCheck.input(itemIndex < getItemCount(categoryIndex));
  }

  public void deleteCategory(int index) {
    checkCategoryIndex(index);

    $.removeCategory(index);
    post(ChangeEvent.INSTANCE);
  }

  public void deleteItem(int categoryIndex, int itemIndex) {
    checkItemIndex(categoryIndex, itemIndex);

    Category.Builder c = $.getCategoryBuilder(categoryIndex);
    List<ByteString> ids = new ArrayList<>(c.getItemList());
    ids.remove(itemIndex);
    c.clearItem().addAllItem(ids);
    post(ChangeEvent.INSTANCE);
  }

  public void moveCategory(int index, boolean forward) {
    checkCategoryIndex(index);
    int newIndex = index + (forward ? 1 : -1);
    checkCategoryIndex(newIndex);

    Category temp = $.getCategory(index);
    $.setCategory(index, $.getCategory(newIndex));
    $.setCategory(newIndex, temp);
    post(ChangeEvent.INSTANCE);
  }

  public void moveItem(int categoryIndex, int itemIndex, boolean forward) {
    checkItemIndex(categoryIndex, itemIndex);

    if (forward && (itemIndex == getItemCount(categoryIndex) - 1)) {
      int nextCategoryIndex = categoryIndex + 1;
      checkCategoryIndex(nextCategoryIndex);

      Pad pad = getItem(categoryIndex, itemIndex);
      deleteItem(categoryIndex, itemIndex);
      insertItem(pad, nextCategoryIndex, 0);
    } else if (!forward && (itemIndex == 0)) {
      int previousCategoryIndex = categoryIndex - 1;
      checkCategoryIndex(previousCategoryIndex);

      Pad pad = getItem(categoryIndex, itemIndex);
      deleteItem(categoryIndex, itemIndex);
      insertItem(pad, previousCategoryIndex, getItemCount(previousCategoryIndex));
    } else {
      int newItemIndex = itemIndex + (forward ? 1 : -1);
      checkItemIndex(categoryIndex, newItemIndex);

      Category.Builder c = $.getCategoryBuilder(categoryIndex);
      ByteString temp = c.getItem(itemIndex);
      c.setItem(itemIndex, c.getItem(newItemIndex));
      c.setItem(newItemIndex, temp);
      post(ChangeEvent.INSTANCE);
    }
  }

  private void insertItem(Pad item, int categoryIndex, int position) {
    Category.Builder c = $.getCategoryBuilder(categoryIndex);
    List<ByteString> ids = new ArrayList<>(c.getItemList());
    ids.add(position, item.id());
    c.clearItem().addAllItem(ids);
    post(ChangeEvent.INSTANCE);
  }

  public boolean hasItemLimit() {
    return $.hasItemLimit();
  }

  public int itemLimit() {
    Validate.isTrue(hasItemLimit());
    return $.getItemLimit();
  }

  public void setItemLimit(int value) {
    TestCheck.input(value >= 1);
    TestCheck.input(value <= MAX_ITEMS);
    $.setItemLimit(value);
    if (!$.hasMinItemsPerCategory()) {
      $.setMinItemsPerCategory(0);
    }
    post(ChangeEvent.INSTANCE);
  }

  public void clearItemLimit() {
    $.clearItemLimit();
    $.clearMinItemsPerCategory();
    post(ChangeEvent.INSTANCE);
  }

  public int minItemsPerCategory() {
    Validate.isTrue(hasItemLimit());
    return $.getMinItemsPerCategory();
  }

  public void setMinItemsPerCategory(int value) {
    TestCheck.input(hasItemLimit());
    TestCheck.input(value >= 0);
    TestCheck.input(value <= MAX_ITEMS);
    $.setMinItemsPerCategory(value);
    post(ChangeEvent.INSTANCE);
  }

  public boolean hasDefaultOptions() {
    return !hasItemLimit();
  }

  @Override public void setDefaults(String initialText) {
    formulation().appendText(initialText);
  }
}
